import 'dart:convert';
import 'dart:ui' as ui;
import 'package:fish_redux/fish_redux.dart';
import 'package:flutter/material.dart' hide Action;
import 'package:fluttertoast/fluttertoast.dart';
import 'package:member_center_sdk/sdk.dart';
import 'package:member_center_sdk_example/components/edit_dialog.dart';
import 'package:member_center_sdk_example/components/loading_dialog.dart';
import 'package:member_center_sdk_example/core/auth_type.dart';
import 'package:member_center_sdk_example/models/member.dart';
import 'package:member_center_sdk_example/pages/members/center/passwords/old/page.dart';
import 'package:member_center_sdk_example/pages/members/center/passwords/sms/page.dart';
import 'package:member_center_sdk_example/pages/members/login/page.dart';
import 'package:multi_image_picker/multi_image_picker.dart';
import 'action.dart';
import 'state.dart';

Effect<MemberCenterState> buildEffect() {
  return combineEffects(<Object, Effect<MemberCenterState>>{
    Lifecycle.initState: _init,
    MemberCenterAction.login: _loginAction,
    MemberCenterAction.reload: _reloadAction,
    MemberCenterAction.setEmail: _setEmailAction,
    MemberCenterAction.setNickName: _setNickNameAction,
    MemberCenterAction.setAvater: _setAvaterAction,
    MemberCenterAction.setPassword: _setPasswordAction,
    MemberCenterAction.logout: _logoutAction
  });
}

Future _init(Action action, Context<MemberCenterState> ctx) async {
  await _reloadAction(action, ctx);
}

Future _reloadAction(Action action, Context<MemberCenterState> ctx) async {
  ctx.dispatch(MemberCenterActionCreator.loadingAction());
  var sdk = MemberCenterSdk.get();
  String token = await sdk.getToken(AuthType.login.index);
  if (token.isNotEmpty) {
    var member = Member();
    bool success = await sdk.getMember(AuthType.login.index, member);
    if (success) {
      ctx.dispatch(MemberCenterActionCreator.initAction(member));
      _checkPassword(action, ctx);
    } else {
      ctx.dispatch(MemberCenterActionCreator.loadErrAction());
    }
  } else {
    await _loginAction(action, ctx);
  }
}

Future _checkPassword(Action action, Context<MemberCenterState> ctx) async {
  var sdkResult = await MemberCenterSdk.get()
      .checkPassword(AuthType.login.index, AuthType.login.index);
  if (sdkResult.success) {
    ctx.dispatch(
        MemberCenterActionCreator.updateHasPasswordAction(sdkResult.value));
  }
}

Future _loginAction(Action action, Context<MemberCenterState> ctx) async {
  var sdk = MemberCenterSdk.get();
  String userName = await sdk.getCacheUserName(1);
  var route = MaterialPageRoute(
    builder: (BuildContext buildCtx) => MemberLoginPage().buildPage(userName),
  );
  var loginResult = await Navigator.of(ctx.context).push(route);
  if (loginResult == true) {
    var member = Member();
    bool success = await sdk.getMember(AuthType.login.index, member);
    if (success) {
      ctx.dispatch(MemberCenterActionCreator.initAction(member));
      _checkPassword(action, ctx);
    } else {
      ctx.dispatch(MemberCenterActionCreator.loadErrAction());
    }
  } else {
    ctx.dispatch(MemberCenterActionCreator.noLoginAction());
  }
}

Future _setEmailAction(Action action, Context<MemberCenterState> ctx) async {
  String email = await showDialog(
      context: ctx.context,
      barrierDismissible: false,
      builder: (BuildContext context) => EditDialog(
            title: "邮箱:",
            text: ctx.state.email,
          ));
  if (email != null && email.isNotEmpty) {
    if (await _setExt("{'email':'$email'}")) {
      ctx.dispatch(MemberCenterActionCreator.updateEmailAction(email));
    } else {
      Fluttertoast.showToast(msg: "保存失败");
    }
  }
}

Future _setNickNameAction(Action action, Context<MemberCenterState> ctx) async {
  String nickName = await showDialog(
      context: ctx.context,
      barrierDismissible: false,
      builder: (BuildContext context) => EditDialog(
            title: "昵称:",
            text: ctx.state.nickName,
          ));
  if (nickName != null && nickName.isNotEmpty) {
    if (await _setExt("{'nickName':'$nickName'}")) {
      ctx.dispatch(MemberCenterActionCreator.updateNickNameAction(nickName));
    }
  }
}

Future<bool> _setExt(String json) async {
  var sdkResult =
      await MemberCenterSdk.get().setExt(AuthType.login.index, json);
  if (sdkResult.success) {
    if (sdkResult.value == true) {
      return true;
    } else {
      Fluttertoast.showToast(msg: "服务器保存失败");
      return false;
    }
  } else {
    Fluttertoast.showToast(msg: sdkResult.message);
    return false;
  }
}

Future _setAvaterAction(Action action, Context<MemberCenterState> ctx) async {
  try {
    List<Asset> resultList = await MultiImagePicker.pickImages(
      maxImages: 1,
      enableCamera: true,
    );
    if (ctx.isDisposed) return;
    if (resultList.length > 0) {
      var asset = resultList[0];
      var orgAsset = await asset.requestOriginal(quality: 80);
      var bytes = orgAsset.buffer.asUint8List();
      showLoading(ctx.context);
      var sdkResult =
          await MemberCenterSdk.get().setAvater(AuthType.login.index, bytes);
      closeLoading(ctx.context);
      if (sdkResult.success) {
        ctx.dispatch(
            MemberCenterActionCreator.updateAvaterUrlAction(sdkResult.value));
      } else {
        Fluttertoast.showToast(msg: sdkResult.message);
      }
    }
  } catch (e) {
    print(e);
    Fluttertoast.showToast(msg: "本地发送图片错误");
  }
}

Future _setPasswordAction(Action action, Context<MemberCenterState> ctx) async {
  if (ctx.state.hasPassword == true) {
    var route = MaterialPageRoute(
      builder: (BuildContext buildCtx) => SetPasswordByOldPage().buildPage({}),
    );
    await Navigator.of(ctx.context).push(route);
  } else {
    var sdk = MemberCenterSdk.get();
    String userName = await sdk.getCacheUserName(1);
    var route = MaterialPageRoute(
      builder: (BuildContext buildCtx) =>
          SetPasswordBySmsPage().buildPage(userName),
    );
    var setResult = await Navigator.of(ctx.context).push(route);
    ctx.dispatch(
        MemberCenterActionCreator.updateHasPasswordAction(setResult == true));
  }
}

Future _logoutAction(Action action, Context<MemberCenterState> ctx) async {
  var sdk = MemberCenterSdk.get();
  var result = await sdk.logout(AuthType.login.index);
  if (result == true) {
    ctx.dispatch(MemberCenterActionCreator.noLoginAction());
  } else {
    Fluttertoast.showToast(msg: "登出失败");
  }
}
